import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { inBrowser } from 'vitepress';

const useSelect = (selector: string) => {
  const visible = ref(false); // 是否展示菜单

  const selectRect = ref({
    top: 0,
    left: 0,
    width: 0,
  })

  const x = computed<number>(() => selectRect.value.left + selectRect.value.width / 2);
  const y = computed<number>(() => {
    if (scrollY.value) {
      return scrollY.value;
    }
    return selectRect.value.top - 4;
  });

  const mouseDown = () => {
    visible.value = false;
  };
  const mouseUp = () => {
    scrollY.value = 0;
    const selectionText = window.getSelection()?.toString();
    if (selectionText?.trim()) {
      
      const range = window.getSelection()?.getRangeAt(0);
      const rect = range?.getBoundingClientRect();
      if (rect) {
        selectRect.value = {
          top: rect.top + window.scrollY,
          left: rect.left + window.scrollX,
          width: rect.width,
        }
        visible.value = true;
      } else {
        visible.value = false;
      }
    } else {
      visible.value = false;
    }
  };

  const scrollTop = ref(0); // 当前已滚动距离
  const scrollY = ref(0); // 滚动时popover的位置

  const scroll = ({ target }: { target: HTMLElement } & any) => {
    if (visible.value) {
      scrollY.value = y.value - target.scrollTop + scrollTop.value;
    }
    scrollTop.value = target.scrollTop;
  };

  const addEventListener = () => {
    const ele = document.querySelector(selector) as HTMLElement;
    if (ele) {
      ele.addEventListener('mousedown', mouseDown);
      ele.addEventListener('mouseup', mouseUp);
      const scrollWrapper = document.querySelector('#app > .o-scroller > .o-scroller-container') as HTMLElement;
      if (scrollWrapper) {
        scrollWrapper.addEventListener('scroll', scroll);
      }
    } else {
      requestIdleCallback(addEventListener);
    }
  };

  onMounted(() => {
    if (!inBrowser) return;
    addEventListener();
  });

  onUnmounted(() => {
    if (!inBrowser) return;
    const ele = document.querySelector(selector) as HTMLElement;
    if (!ele) return;
    ele?.removeEventListener('mousedown', mouseDown);
    ele?.removeEventListener('mouseup', mouseUp);
    const scrollWrapper = document.querySelector('#app > .o-scroller > .o-scroller-container');
    if (scrollWrapper) {
      scrollWrapper.removeEventListener('scroll', scroll);
    }
  });

  return {
    x,
    y,
    visible,
  };
};

export default useSelect;